#include "reader.h"

namespace SkyID
{

ReaderZip::ReaderZip(const char* archiveName, const char* fileName)
{
	mFile = unzOpen(archiveName);
	if (!mFile)
    {
		LOG_MSG("ReaderZip: cannot open file '%s'", archiveName);
		return;
	}

	if (unzLocateFile(mFile, fileName, 0) != UNZ_OK)
	{
		unzClose(mFile);
		mFile = NULL;
		LOG_MSG("ZipReader: cannot find file '%s' in archive '%s'", fileName, archiveName);
		return;
	}

	unz_file_info fileInfo;

	if (unzGetCurrentFileInfo(mFile, &fileInfo, 0,0, 0,0, 0,0) != UNZ_OK)
	{
		unzClose(mFile);
		mFile = NULL;
		LOG_MSG("ZipReader: cannot get info for file '%s' in archive '%s'", fileName, archiveName);
		return;
	}

	mSize = fileInfo.uncompressed_size;

	if (unzOpenCurrentFile(mFile) != UNZ_OK)
	{
		unzClose(mFile);
		mFile = NULL;
		LOG_MSG("ZipReader: cannot open file '%s' in archive '%s'", fileName, archiveName);
		return;
	}

	setValid(true);
}

ReaderZip::~ReaderZip()
{
	if (mFile)
	{
		unzCloseCurrentFile(mFile);
		unzClose(mFile);
	}
}

uint32 ReaderZip::read(void *buffer, uint32 size)
{
	LOG_ASSERT(mFile);
	return (uint32)unzReadCurrentFile(mFile, buffer, size);
}

uint32 ReaderZip::tell() const
{
	LOG_ASSERT(mFile);
	return (uint32)unztell(mFile);
}

bool ReaderZip::reset()
{
	if (!mFile)
		return false;
	unzCloseCurrentFile(mFile);
	unzOpenCurrentFile(mFile);
	return true;
}

} // namespace SkyID
